from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, UniqueConstraint
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from datetime import datetime

Base = declarative_base()

class Plate(Base):
    """料盘模型"""
    __tablename__ = "plates"
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(50), unique=True, nullable=False)  # AGV1, AGV2, TB1, FL1
    capacity = Column(Integer, nullable=False, default=10)  # 料位数量
    description = Column(String(200), default="")
    created_at = Column(DateTime, default=datetime.now)
    
    # 关联料位
    positions = relationship("Position", back_populates="plate", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<Plate(name='{self.name}', capacity={self.capacity})>"

class Position(Base):
    """料位模型"""
    __tablename__ = "positions"
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    plate_id = Column(Integer, ForeignKey("plates.id"), nullable=False)
    position_index = Column(Integer, nullable=False)  # 料位索引(0开始)
    sample_id = Column(String(100), default="")  # 样品ID，空字符串表示空位
    status = Column(String(20), default="available")  # available, occupied, disabled
    
    # 任务追踪字段
    task_id = Column(String(100), default="")  # 任务ID，记录是哪个任务操作的
    task_type = Column(String(50), default="")  # 任务类型：place, remove, transfer等
    operator = Column(String(50), default="")  # 操作员/系统标识
    operation_time = Column(DateTime, default=datetime.now)  # 操作时间
    
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
    
    # 关联料盘
    plate = relationship("Plate", back_populates="positions")
    
    # 唯一约束：同一料盘的料位索引不能重复
    __table_args__ = (UniqueConstraint('plate_id', 'position_index', name='uq_plate_position'),)
    
    def __repr__(self):
        return f"<Position(plate_id={self.plate_id}, index={self.position_index}, sample='{self.sample_id}', task='{self.task_id}')>"

class Config(Base):
    """配置模型"""
    __tablename__ = "config"
    
    key = Column(String(100), primary_key=True)
    value = Column(String(500), nullable=False)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
    
    def __repr__(self):
        return f"<Config(key='{self.key}', value='{self.value}')>" 